#!/usr/bin/env python3
"""
项目环境设置脚本
用于自动化管理虚拟环境、安装依赖和配置环境变量
"""

import os
import sys
import subprocess
import shutil
from pathlib import Path


class WebMonitorSetup:
    def __init__(self):
        self.project_root = Path(__file__).parent
        self.venv_name = "web-venv"
        self.venv_path = self.project_root / self.venv_name
        self.requirements_file = self.project_root / "requirements.txt"
        self.env_file = self.project_root / ".env"
        self.env_example_file = self.project_root / ".env.example"
        
    def print_step(self, message):
        """打印步骤信息"""
        print(f"\n{'='*50}")
        print(f"[步骤] {message}")
        print(f"{'='*50}")
    
    def run_command(self, command, capture_output=False):
        """执行系统命令"""
        try:
            if capture_output:
                result = subprocess.run(command, shell=True, capture_output=True, text=True)
                return result.returncode == 0, result.stdout, result.stderr
            else:
                result = subprocess.run(command, shell=True)
                return result.returncode == 0
        except Exception as e:
            print(f"命令执行失败: {e}")
            return False
    
    def check_virtual_env(self):
        """检查虚拟环境是否存在"""
        self.print_step("检查虚拟环境状态")
        
        if self.venv_path.exists():
            print(f"找到现有虚拟环境: {self.venv_path}")
            
            # 检查虚拟环境是否完整
            if sys.platform == "win32":
                python_exe = self.venv_path / "Scripts" / "python.exe"
            else:
                python_exe = self.venv_path / "bin" / "python"
            
            if python_exe.exists():
                print("虚拟环境完整且可用")
                
                rebuild = input("是否要重新构建虚拟环境？(y/N): ").lower().strip()
                if rebuild == 'y':
                    print("删除现有虚拟环境...")
                    shutil.rmtree(self.venv_path)
                    return False
                return True
            else:
                print("虚拟环境不完整，需要重新构建")
                shutil.rmtree(self.venv_path)
                return False
        else:
            print("未找到虚拟环境")
            return False
    
    def create_virtual_env(self):
        """创建虚拟环境"""
        self.print_step("创建虚拟环境")
        
        print(f"正在创建虚拟环境: {self.venv_name}")
        success = self.run_command(f"python -m venv {self.venv_path}")
        
        if success:
            print("虚拟环境创建成功！")
            return True
        else:
            print("虚拟环境创建失败！")
            return False
    
    def get_activation_command(self):
        """获取虚拟环境激活命令"""
        if sys.platform == "win32":
            return f"{self.venv_path}\\Scripts\\activate"
        else:
            return f"source {self.venv_path}/bin/activate"
    
    def get_python_path(self):
        """获取虚拟环境中的Python路径"""
        if sys.platform == "win32":
            return self.venv_path / "Scripts" / "python.exe"
        else:
            return self.venv_path / "bin" / "python"
    
    def install_dependencies(self):
        """安装项目依赖"""
        self.print_step("安装项目依赖")
        
        if not self.requirements_file.exists():
            print("未找到requirements.txt文件！")
            return False
        
        python_path = self.get_python_path()
        
        print("正在安装依赖包...")
        success = self.run_command(f"{python_path} -m pip install --upgrade pip")
        if not success:
            print("pip升级失败！")
            return False
        
        success = self.run_command(
            f"{python_path} -m pip install -r {self.requirements_file} "
            f"-i https://mirrors.aliyun.com/pypi/simple/ "
            f"--trusted-host mirrors.aliyun.com"
        )
        if success:
            print("依赖安装成功！")
            return True
        else:
            print("依赖安装失败！")
            return False
    
    def check_env_file(self):
        """检查环境配置文件"""
        self.print_step("检查环境配置文件")
        
        if self.env_file.exists():
            print("找到.env环境配置文件")
            return True
        else:
            print("未找到.env环境配置文件")
            
            if self.env_example_file.exists():
                create_env = input("是否要根据.env.example创建.env文件？(Y/n): ").lower().strip()
                if create_env != 'n':
                    try:
                        shutil.copy2(self.env_example_file, self.env_file)
                        print("已创建.env环境配置文件")
                        return True
                    except Exception as e:
                        print(f"创建.env文件失败: {e}")
                        return False
                else:
                    print("跳过创建.env文件")
                    return False
            else:
                print("未找到.env.example模板文件")
                self.create_default_env()
                return True
    
    def create_default_env(self):
        """创建默认的.env文件"""
        print("创建默认的.env配置文件...")
        
        default_env_content = """# 环境变量配置文件
# 请根据实际情况修改以下配置

# Kafka配置
KAFKA_BOOTSTRAP_SERVERS=localhost:9092
KAFKA_TOPIC=web-monitor
KAFKA_GROUP_ID=web-monitor-group

# OSS存储配置  
OSS_ENDPOINT=
OSS_ACCESS_KEY_ID=
OSS_ACCESS_KEY_SECRET=
OSS_BUCKET_NAME=

# 数据库配置
DATABASE_URL=sqlite:///./webmonitor.db

# ===== 日志级别（可选，默认为 INFO） =====
LOG_LEVEL=INFO

# ===== 其他配置 =====
MAX_MESSAGE_LENGTH=1000
ENABLE_LOGGING=True

# API配置
API_PORT=8000
API_HOST=0.0.0.0
"""
        
        try:
            with open(self.env_file, 'w', encoding='utf-8') as f:
                f.write(default_env_content)
            print(f"已创建默认.env配置文件: {self.env_file}")
        except Exception as e:
            print(f"创建默认.env文件失败: {e}")
    
    def check_env_config(self):
        """检查环境配置中的关键配置项"""
        self.print_step("检查环境配置")
        
        if not self.env_file.exists():
            print("未找到.env文件，跳过配置检查")
            return False
        
        try:
            with open(self.env_file, 'r', encoding='utf-8') as f:
                env_content = f.read()
            
            # 检查Kafka配置
            kafka_found = False
            if 'KAFKA_BOOTSTRAP_SERVERS' in env_content:
                kafka_config = [line for line in env_content.split('\n') 
                              if line.startswith('KAFKA_BOOTSTRAP_SERVERS=') and not line.startswith('#')]
                if kafka_config:
                    kafka_value = kafka_config[0].split('=', 1)[1].strip()
                    if kafka_value and kafka_value != '':
                        print(f"✓ 找到Kafka配置: {kafka_value}")
                        kafka_found = True
            
            if not kafka_found:
                print("⚠ 未找到有效的Kafka配置，请在.env文件中配置KAFKA_BOOTSTRAP_SERVERS")
            
            # 检查OSS配置
            oss_found = False
            oss_fields = ['OSS_ENDPOINT', 'OSS_ACCESS_KEY_ID', 'OSS_ACCESS_KEY_SECRET', 'OSS_BUCKET_NAME']
            oss_config = {}
            
            for field in oss_fields:
                if field in env_content:
                    field_config = [line for line in env_content.split('\n') 
                                  if line.startswith(f'{field}=') and not line.startswith('#')]
                    if field_config:
                        field_value = field_config[0].split('=', 1)[1].strip()
                        oss_config[field] = field_value
            
            if len(oss_config) == 4 and all(oss_config.values()):
                print(f"✓ 找到完整的OSS配置")
                oss_found = True
            else:
                print("⚠ OSS配置不完整，请在.env文件中配置所有OSS相关变量")
            
            return kafka_found and oss_found
            
        except Exception as e:
            print(f"读取.env文件失败: {e}")
            return False
    
    def print_activation_info(self):
        """打印激活信息"""
        self.print_step("环境设置完成")
        
        activation_cmd = self.get_activation_command()
        
        print("虚拟环境设置完成！")
        print(f"\n要激活虚拟环境，请运行:")
        print(f"  {activation_cmd}")
        print(f"\n虚拟环境路径: {self.venv_path}")
        print(f"项目根目录: {self.project_root}")
        
        if self.env_file.exists():
            print(f"\n请检查并修改环境配置文件: {self.env_file}")
        
        print(f"\n运行项目:")
        if sys.platform == "win32":
            print(f"  {self.venv_path}\\Scripts\\python.exe main.py")
        else:
            print(f"  {self.venv_path}/bin/python main.py")
    
    def setup(self):
        """执行完整的环境设置流程"""
        print("Web Monitor 项目环境设置")
        print("="*50)
        
        # 1. 检查虚拟环境
        venv_exists = self.check_virtual_env()
        
        # 2. 如果虚拟环境不存在，创建它
        if not venv_exists:
            if not self.create_virtual_env():
                print("虚拟环境创建失败，退出设置")
                return False
        
        # 3. 安装依赖
        if not self.install_dependencies():
            print("依赖安装失败，退出设置")
            return False
        
        # 4. 检查环境配置文件
        self.check_env_file()
        
        # 5. 检查环境配置
        self.check_env_config()
        
        # 6. 显示激活信息
        self.print_activation_info()
        
        return True


def main():
    """主函数"""
    setup = WebMonitorSetup()
    
    try:
        success = setup.setup()
        if success:
            print("\n环境设置完成！")
            sys.exit(0)
        else:
            print("\n环境设置失败！")
            sys.exit(1)
    except KeyboardInterrupt:
        print("\n设置被用户中断")
        sys.exit(1)
    except Exception as e:
        print(f"\n设置过程中出现错误: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
